Popular Searches
Popular Course Categories
Popular Courses

Compiling Java Programs Using javac

Compiling Java Programs Using javac

Java Installation and Development Environment Setup

Compiling Java Programs Using javac

Course: Core Java Training

Topic: Compiling Java Programs Using javac

Course Link: Core Java Training Course

Demo Link: Register for a Course Demo

Website: JustAcademy Official Website


1. Introduction to Java Compilation

Java compilation is the process of translating Java source code into bytecode that can be executed by the Java Virtual Machine (JVM). The Java compiler, called javac, is provided by the Java Development Kit (JDK).

When a programmer writes a Java program, the code is usually saved in a file with the .java extension. The compiler checks the source code for syntax and type-related errors and, when compilation succeeds, generates one or more .class files containing Java bytecode.

The JVM then executes the compiled bytecode. This separation between compilation and execution helps Java programs run on different platforms that provide compatible Java runtime environments.

Learning Objectives

  • Understand the purpose of the Java compiler.
  • Differentiate Java source code, bytecode, and class files.
  • Compile and execute a Java program using Command Prompt or Terminal.
  • Compile multiple Java source files together.
  • Understand common javac command-line options.
  • Specify an output directory and target Java version.
  • Identify and resolve common compilation errors.

2. What Is javac?

javac is the Java compiler command used to compile Java source files. It reads source code containing class, interface, and other Java declarations and generates class files that can be executed by a compatible JVM.

The compiler is included with the JDK. A basic Java runtime installation alone may not provide the development tools needed to compile source code.

Key Responsibilities of javac

  • Read Java source files ending in .java.
  • Check Java syntax and type correctness.
  • Check access rules and resolve referenced types.
  • Report compilation errors and warnings.
  • Generate bytecode in .class files.
  • Support options for output directories, classpaths, debugging information, and target Java releases.

Basic Syntax

javac [options] SourceFile.java

Here, javac is the compiler command, options are optional configuration arguments, and SourceFile.java is the Java source file to compile.

3. Understanding Source Code, Bytecode, and Class Files

Java development typically involves three important stages: writing source code, compiling it into bytecode, and executing that bytecode using the JVM.

File or Component Description Example
Java source file Contains the program written by the developer. HelloJava.java
Java compiler Checks and compiles Java source code. javac
Bytecode class file Contains compiled Java bytecode. HelloJava.class
Java Virtual Machine Loads and executes the compiled bytecode. JVM provided by a compatible Java runtime.

Compilation Workflow

Java Source Code (.java)
          |
          v
       javac
          |
          v
Compiled Bytecode (.class)
          |
          v
          JVM
          |
          v
      Program Output

Important: The javac command compiles the source code; the java command launches a Java application. They perform different tasks.

4. Prerequisites for Using javac

Before compiling Java programs, ensure that the required development tools are installed and accessible.

  • Install a compatible JDK.
  • Confirm that the JDK contains the Java compiler.
  • Configure PATH if you want to run javac without typing its full path.
  • Open a terminal or command-line interface.
  • Create a Java source file with the correct file extension.
  • Know the directory in which the source file is saved.

Verify the Compiler Installation

javac -version

The command should display the installed compiler version. If the command is not recognized, check the JDK installation and PATH configuration.

5. Creating Your First Java Program

Before compiling a program, create a Java source file. In this example, the class is named HelloJava, so the source file should be named HelloJava.java.

Step 1: Write the Source Code

public class HelloJava {
    public static void main(String[] args) {
        System.out.println("Hello, Java!");
    }
}

Step 2: Save the File

Save the program as:

HelloJava.java

When a top-level class is declared public, its source file must use the same name as that class, with the .java extension. Java is also case-sensitive, so HelloJava.java is different from hellojava.java on many systems.

Step 3: Open the Terminal

Open Command Prompt, PowerShell, or Terminal and navigate to the folder containing the source file.

For example, if the file is stored in a folder named JavaPractice, change to that directory before compiling.

6. Compiling a Java Program Using javac

Once the source file has been created, use the compiler to generate the class file.

Step 1: Compile the Program

javac HelloJava.java

This command asks the compiler to compile the source file. If compilation succeeds, a file named HelloJava.class is normally created in the current directory.

Step 2: Check the Generated Class File

List the files in the current directory and confirm that HelloJava.class exists. The source file remains available for further editing.

Step 3: Run the Compiled Program

java HelloJava

Expected output:

Hello, Java!

Do not include .java or .class in the basic launch command. Use the class name when launching a traditional class-based Java application.

7. What Happens During Compilation?

The Java compiler performs several checks and transformations before producing class files.

7.1 Reading the Source Code

The compiler reads the contents of the source file and identifies Java language elements such as declarations, statements, expressions, and types.

7.2 Syntax Checking

The compiler checks whether the program follows Java grammar rules. Missing semicolons, unmatched braces, and incorrectly formed statements can cause compilation errors.

7.3 Type Checking and Semantic Analysis

The compiler checks whether operations are compatible with the types involved and whether referenced classes, methods, and variables can be resolved correctly.

7.4 Bytecode Generation

If the required compilation checks succeed, the compiler generates class files containing Java bytecode and related metadata.

7.5 Runtime Execution

The JVM loads the compiled classes and executes the program. Some errors, including many logic errors and certain runtime exceptions, are not detected during compilation.

8. Compiling Multiple Java Files

Java applications often contain multiple classes in separate source files. The compiler can compile related source files together and resolve dependencies between them.

Example: Two Java Classes

Create a file named Message.java:

public class Message {
    public void display() {
        System.out.println("Welcome to Core Java!");
    }
}

Create another file named MainApp.java:

public class MainApp {
    public static void main(String[] args) {
        Message message = new Message();
        message.display();
    }
}

Compile Both Files

javac Message.java MainApp.java

Alternatively, if the compiler can locate the source dependency automatically, compiling the main source file may also work:

javac MainApp.java

The exact behavior depends on the source path, classpath, package structure, and compilation options. For predictable beginner exercises, compiling all related source files together is a useful approach.

Run the Application

java MainApp

Expected output:

Welcome to Core Java!

9. Compiling Java Programs with Packages

Packages organize related Java classes and help avoid naming conflicts. A package declaration generally appears at the beginning of a source file, before import statements and class declarations.

Example Source File

Create a file at the path src/com/example/Welcome.java:

package com.example;

public class Welcome {
    public static void main(String[] args) {
        System.out.println("Java packages are useful!");
    }
}

Compile the Packaged Class

From the project directory, run:

javac -d out src/com/example/Welcome.java

The -d out option tells the compiler to place generated class files in the out directory. The compiler creates the package directory structure under that destination when necessary.

Run the Packaged Class

java -cp out com.example.Welcome

Expected output:

Java packages are useful!

When running a packaged class, use its fully qualified name, including the package name, and ensure the classpath points to the directory above the package hierarchy.

10. Important javac Command-Line Options

The compiler supports options that control where class files are created, which classes and libraries are available, and which Java release the code targets.

Option Purpose Example
-d Specifies the destination directory for generated class files. javac -d out HelloJava.java
-cp or -classpath Specifies where to find user classes and libraries. javac -cp lib/example.jar App.java
--release Compiles using the language rules and supported APIs of a specified Java release, when supported by the installed JDK. javac --release 17 App.java
-g Includes debugging information in class files. javac -g App.java
-encoding Specifies the character encoding of source files. javac -encoding UTF-8 App.java
-verbose Displays detailed information about compilation activities. javac -verbose App.java
-Xlint Enables compiler warnings for selected categories. javac -Xlint:all App.java
-version Displays compiler version information. javac -version
-help or --help Displays compiler command help. javac --help

11. Using the -d Option to Organize Class Files

By default, javac normally places generated class files alongside their corresponding source files. In projects with many classes, keeping generated files separate from source files can make the project easier to manage.

Example Directory Structure

JavaProject/
    src/
        HelloJava.java
    out/

Compile to the Output Directory

From the project directory, run:

javac -d out src/HelloJava.java

For a class without a package declaration, the generated file will normally be:

out/HelloJava.class

Run the Compiled Class

java -cp out HelloJava

The -cp out option tells the Java launcher to search the output directory for the class.

12. Compiling with a Specific Java Release

Java projects sometimes need to support a particular Java release. The --release option allows a compatible installed JDK to compile code using the language rules and supported Java APIs of the selected release.

Example

javac --release 17 HelloJava.java

This example targets Java 17. The selected release must be supported by the installed compiler.

Important: Compiling for an older release does not guarantee that the program will run on every system. The runtime must be compatible with the generated class-file version, and the program must not depend on incompatible external libraries or APIs.

Why Use --release?

  • To build applications intended for an older Java platform.
  • To detect use of APIs unavailable in the selected release.
  • To make the target platform explicit in a build process.
  • To improve consistency between development and deployment environments.

13. Using the Classpath During Compilation

The classpath tells Java development tools where to find user-defined classes and external libraries needed by a program. It is different from PATH, which helps the operating system locate executable commands.

Example with a Library

Suppose an application depends on a library stored in lib/example.jar. A compilation command can include that library:

javac -cp lib/example.jar -d out src/App.java

Here, -cp specifies the classpath, and -d out specifies where generated class files should be placed.

When running the program, include both the application output directory and the required library in the runtime classpath.

Windows Example

java -cp "out;lib/example.jar" App

macOS or Linux Example

java -cp "out:lib/example.jar" App

Windows normally separates classpath entries with a semicolon, while macOS and Linux normally use a colon.

14. Understanding Compilation Errors

A compilation error occurs when the compiler cannot successfully compile the supplied source code. The compiler usually reports the source file, line number, and a description of the problem.

Example 1: Missing Semicolon

public class Test {
    public static void main(String[] args) {
        System.out.println("Hello")
    }
}

Problem: The print statement is missing a semicolon.

Corrected code:

public class Test {
    public static void main(String[] args) {
        System.out.println("Hello");
    }
}

Example 2: Incorrect File Name

If the source file contains a public class named Student, save the file as Student.java.

public class Student {
    public static void main(String[] args) {
        System.out.println("Student class");
    }
}

Compile it with:

javac Student.java

Example 3: Undefined Variable

public class Demo {
    public static void main(String[] args) {
        System.out.println(total);
    }
}

Problem: The variable total has not been declared in the visible scope.

Correction: Declare and initialize the variable before using it.

public class Demo {
    public static void main(String[] args) {
        int total = 100;
        System.out.println(total);
    }
}

15. Common javac Errors and Their Solutions

Error or Symptom Possible Cause Solution
javac is not recognized The JDK bin directory is not available through PATH. Verify the JDK installation and update PATH, then open a new terminal.
file not found The terminal is in the wrong directory or the file name is incorrect. Check the current directory and the exact source file name.
class ... is public, should be declared in a file named ... The public class name and source file name do not match. Rename the source file to match the public class name.
';' expected A semicolon is missing in a statement or another syntax issue exists nearby. Review the reported line and nearby code.
cannot find symbol A variable, method, or type is misspelled, undeclared, or unavailable. Check spelling, declarations, imports, classpath, and source files.
package ... does not exist A required package or library cannot be found during compilation. Check imports, dependency availability, classpath, and module configuration.
illegal start of expression The code contains invalid syntax, often near braces or declarations. Check the surrounding code structure and statement placement.
unsupported release The selected compiler does not support the requested release. Use a JDK that supports the target release or choose a supported target.
class file has wrong version A class was compiled for a newer or incompatible Java version. Use a compatible JDK or rebuild dependencies for the required target.
Compilation succeeds but the program will not launch The runtime classpath, package name, main class, or runtime version may be incorrect. Check the launch command, classpath, main method, and runtime compatibility.

16. Difference Between Compilation Errors and Runtime Errors

Feature Compilation Error Runtime Error
When it occurs During compilation. While the program is executing, or during class loading or initialization.
Detected by Usually the Java compiler. The JVM or application execution environment.
Example Missing semicolon or incompatible type assignment. NullPointerException during execution.
Does a class file get generated? A failed compilation may produce no class file for the failed source, though other class files may have been generated. The program has generally been compiled, but execution fails at runtime.
Solution Correct the source code or compilation configuration. Investigate the stack trace, program state, data, and runtime environment.

17. Best Practices for Compiling Java Programs

  • Use a JDK version compatible with your project requirements.
  • Use meaningful class names and matching source file names for public top-level classes.
  • Compile from the correct project directory.
  • Use the -d option to separate generated class files from source code.
  • Use --release when a project must target a specific supported Java release.
  • Use explicit classpaths when compiling programs that depend on external libraries.
  • Read the first compiler error carefully and correct errors before moving to later messages.
  • Use -Xlint to inspect additional warnings when appropriate.
  • Keep source code organized according to package names.
  • Use build tools such as Maven or Gradle for larger projects with many dependencies.
  • Recompile source files after making changes.
  • Test the compiled program separately from the compilation step.

18. Practical Exercises

Exercise 1: Compile a Basic Program

Create Welcome.java with a main method that prints a welcome message. Compile it using javac and run the generated class file.

Exercise 2: Identify a Compilation Error

Remove a semicolon from a print statement and compile the program. Read the error message, correct the code, and compile again.

Exercise 3: Compile Multiple Files

Create two classes, such as Calculator.java and CalculatorDemo.java. Compile both files together and execute the demo class.

Exercise 4: Use the -d Option

Compile a Java program into an output directory named out. Run it using java -cp out ClassName.

Exercise 5: Compile a Package

Create a class inside a package, compile it with -d, and run it using the fully qualified class name.

Exercise 6: Use Compiler Warnings

Compile a small program using javac -Xlint:all. Review the warnings and determine which changes would improve the code.

Exercise 7: Target a Java Release

If your installed JDK supports it, compile a basic program with javac --release 17 ClassName.java. Explain what the release option controls.

19. Mini Project: Student Marks Calculator

Create a Java program that calculates the total and average marks for a student. This project provides practice in writing source code, compiling it, and running the resulting class file.

Source Code

public class StudentMarks {
    public static void main(String[] args) {
        int math = 85;
        int science = 90;
        int english = 80;

        int total = math + science + english;
        double average = total / 3.0;

        System.out.println("Total Marks: " + total);
        System.out.println("Average Marks: " + average);
    }
}

Compile the Program

javac StudentMarks.java

Run the Program

java StudentMarks

Expected Output

Total Marks: 255
Average Marks: 85.0

Experiment by changing the marks, compiling the program again, and running it to observe the updated output.

20. Interview Questions and Answers

Q1. What is javac?

Answer: javac is the Java compiler included with the JDK. It compiles Java source code into class files containing bytecode.

Q2. What is the basic javac command?

Answer: The basic command is javac FileName.java, where the file name identifies the source file to compile.

Q3. What is the difference between javac and java?

Answer: javac compiles Java source code, while java launches a Java application using the JVM.

Q4. What is a .class file?

Answer: A class file contains compiled Java bytecode and related metadata that the JVM can load.

Q5. What happens when compilation fails?

Answer: The compiler reports errors that must be corrected. A failed compilation may leave no class file for the affected source, although other output files may already exist.

Q6. Why must a public class name match its source file name?

Answer: Java requires a public top-level class to be declared in a source file with the same name, using the .java extension.

Q7. What is the purpose of the -d option?

Answer: The -d option specifies the destination directory for generated class files.

Q8. What does the -cp option do?

Answer: The -cp or -classpath option identifies locations containing user classes and libraries required during compilation or execution.

Q9. What is the purpose of --release?

Answer: The --release option lets javac compile using the language rules and supported APIs of a specified Java release, provided the installed JDK supports that release.

Q10. Can javac compile multiple source files together?

Answer: Yes. Multiple source files can be supplied in a single command, allowing the compiler to resolve dependencies between the files.

Q11. What is the difference between a syntax error and a runtime error?

Answer: A syntax error prevents successful compilation. A runtime error occurs during program execution or runtime class loading and initialization.

Q12. How can compiler warnings be displayed?

Answer: Use javac -Xlint:all FileName.java to request a broad set of compiler warnings.

21. Quick Revision Checklist

  • Understand the role of javac in Java development.
  • Know the difference between source code, bytecode, and class files.
  • Verify the compiler using javac -version.
  • Compile a Java file with javac FileName.java.
  • Execute the compiled class using java ClassName.
  • Compile multiple source files together.
  • Use -d to organize generated class files.
  • Understand classpaths and package directory structures.
  • Use --release to target a supported Java release.
  • Recognize common compiler errors and warnings.
  • Compile and run a small project independently.

22. Conclusion

The javac compiler is a fundamental tool in Core Java development. It translates Java source code into bytecode, checks source code for compilation problems, and produces class files that can be executed by a compatible JVM.

By learning basic compilation commands, compiling multiple files, managing output directories and classpaths, targeting compatible Java releases, and troubleshooting compiler errors, learners can build a strong foundation for Java programming.

For structured Java learning resources, visit the JustAcademy Core Java Training Course, register for a course demo, or explore the JustAcademy official website.

whatsapp